package stone926.mods.more_enchantments.screen;

import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.screen.*;
import org.jetbrains.annotations.Nullable;
import stone926.mods.more_enchantments.blocks.GoldenAnvilBlock;
import stone926.mods.more_enchantments.tags.MyBlockTags;
import stone926.mods.more_enchantments.util.RandomUtil;

public class GoldenAnvilBlockScreenHandler extends ForgingScreenHandler {

  private final PropertyDelegate delegate;

  public GoldenAnvilBlockScreenHandler(@Nullable ScreenHandlerType<?> type, int syncId, PlayerInventory playerInventory, ScreenHandlerContext context) {
    super(type, syncId, playerInventory, context);
    delegate = new ArrayPropertyDelegate(2);
    delegate.set(0, 0); // levelCost
    delegate.set(1, 0); // lapisCost
    this.addProperties(delegate);
  }

  @Override
  protected boolean canTakeOutput(PlayerEntity player, boolean present) {
    int levelCost = delegate.get(0);
    return player.isCreative() || player.experienceLevel >= levelCost;
  }

  @Override
  protected void onTakeOutput(PlayerEntity player, ItemStack stack) {
    int levelCost = delegate.get(0);
    int lapisCost = delegate.get(1);
    ItemStack stack1 = input.getStack(1);
    stack1.decrement(lapisCost);
    input.setStack(0, ItemStack.EMPTY);
    if (!player.isCreative()) {
      player.addExperienceLevels(-levelCost);
      context.run(((world, pos) -> RandomUtil.runIfPossible(0.8, world.random, () -> world.setBlockState(pos, GoldenAnvilBlock.getLandingState(world.getBlockState(pos))))));
    }
  }

  @Override
  protected boolean canUse(BlockState state) {
    return state.isIn(MyBlockTags.GOLDEN_ANVIL);
  }

  @Override
  public void updateResult() {
    ItemStack firstStack = input.getStack(0);
    ItemStack secondStack = input.getStack(1);
    ItemStack output = firstStack.copy();
    int repairCost = firstStack.getRepairCost();
    int lapisInputCount;
    if (repairCost > 0 && secondStack.isOf(Items.LAPIS_LAZULI) || secondStack.isOf(Items.LAPIS_BLOCK)) {
      delegate.set(0, repairCost);
      delegate.set(1, repairCost);
      if (secondStack.isOf(Items.LAPIS_LAZULI)) {
        lapisInputCount = secondStack.getCount();
      } else {
        lapisInputCount = secondStack.getCount() * 9;
        delegate.set(1, (int) Math.ceil(repairCost / 9F));
      }
      if (lapisInputCount > repairCost) {
        output.setRepairCost(0);
        this.output.setStack(0, output);
      }
    }
    this.sendContentUpdates();
  }

}
